package com.netease.financial.common.util;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

import cn.trinea.android.common.util.ImageUtils;

/**
 * Created by wyf on 7/20/15.
 */
public class ImageUtil {

    private static final String TAG = ImageUtil.class.getSimpleName();

    public static void displayImage(ImageView imageView, String imageUrl, @DrawableRes int defaultResId) {
        displayImage(imageView, imageUrl, defaultResId, defaultResId, defaultResId);
    }

    public static void displayImage(ImageView imageView, String imageUrl, @DrawableRes int resIdOnLoading,
                                    @DrawableRes int resIdForEmpty, @DrawableRes int resIdOnFail) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(resIdOnLoading)
                .showImageForEmptyUri(resIdForEmpty)
                .showImageOnFail(resIdOnFail)
                .resetViewBeforeLoading(false)  // default
                .delayBeforeLoading(0)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
                .bitmapConfig(Bitmap.Config.ARGB_8888)              // default
                .displayer(new SimpleBitmapDisplayer()) // default 可以设置动画，比如圆角或者渐变
                .handler(new Handler())                             // default
                .build();

        ImageLoader.getInstance().displayImage(
                imageUrl,
                imageView,
                options);
    }

    public static Bitmap getThumbnail(String imageUrl) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        FutureTask<Bitmap> futureTask = new FutureTask<>(new GetBitmapFromUrlTask(imageUrl));
        executorService.submit(futureTask);
        Bitmap bitmap;

        try {
            bitmap = futureTask.get(2000L, TimeUnit.MILLISECONDS);
            executorService.shutdown();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final class GetBitmapFromUrlTask implements Callable<Bitmap> {
        private static final int READ_TIME_OUT_MILLIS = 2000;
        private String mImageUrl;

        public GetBitmapFromUrlTask(String imageUrl) {
            mImageUrl = imageUrl;
        }

        @Override
        public Bitmap call() throws Exception {
            return ImageUtils.getBitmapFromUrl(mImageUrl, READ_TIME_OUT_MILLIS);
        }
    }

    /**
     * Bitmap rotation method
     *
     * @param bitmap  The input bitmap
     * @param degrees The rotation angle
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees != 0 && bitmap != null) {
            final Matrix m = new Matrix();
            final int w = bitmap.getWidth();
            final int h = bitmap.getHeight();
            m.setRotate(degrees, (float) w / 2, (float) h / 2);

            try {
                final Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);
                if (bitmap != rotatedBitmap && rotatedBitmap != null) {
                    bitmap.recycle();
                    bitmap = rotatedBitmap;
                }
            } catch (OutOfMemoryError ex) {
                NfsLog.e(TAG, "OOM in rotateBitmap", ex);
                // We have no memory to rotate. Return the original bitmap.
            }
        }

        return bitmap;
    }

}
